//
//  HMNetworkTools.swift
//  Swift网络请求封装
//
//  Created by HM on 16/9/20.
//  Copyright © 2016年 HM. All rights reserved.
//

import UIKit
import AFNetworking

//  网络请求类型
enum RequestType: Int {
    // get请求
    case GET
    // post请求
    case POST
}

//  网络请求封装类
class HMNetworkTools: AFHTTPSessionManager {

    //  单例全局访问点
    static let sharedTools: HMNetworkTools = {
        let tools = HMNetworkTools()
        //  添加可以接受的响应数据类型
        tools.responseSerializer.acceptableContentTypes?.insert("text/html")
        tools.responseSerializer.acceptableContentTypes?.insert("text/plain")
        tools.requestSerializer = AFJSONRequestSerializer()
        tools.requestSerializer.setValue("application/json", forHTTPHeaderField: "Content-Type")
        
        return tools
    
    }()
    
    //  封装get/post请求
    func request(type: RequestType, url: String, params: Any?, callBack: @escaping (Any?, Error?)->()) {
        
        if type == .GET {
            get(url, parameters: params, progress: nil, success: { (_, response) in
                callBack(response, nil)
                }, failure: { (_, error) in
                    callBack(nil, error)
            })
            
        } else {
            post(url, parameters: params, progress: nil, success: { (_, response) in
                callBack(response, nil)
                }, failure: { (_, error) in
                callBack(nil, error)
            })
            
        }
        
    }
    
    
    
    
}
